<script setup>
import { ref, onMounted } from 'vue'

const isZero = ref(false)

const props = defineProps({
  value: {
    type: Number,
    default: 1
  },
  stockTotal: {
    type: Number
  }
})

const emit = defineEmits(['update:value'])

const handleAdd = () => {
  if (props.value >= 1000) return
  emit('update:value', props.value + 1)
}

const handleSub = () => {
  if (props.value <= 0) return
  emit('update:value', props.value - 1)
}

const handleChange = (e) => {
  const num = +e.target.value
  // 如果不是数字，或者小于1，则不修改
  if (isNaN(num) || num < 0 || num > props.stockTotal || num > 1000) {
    e.target.value = props.value
    return
  }
  emit('update:value', num)
}

onMounted(() => {
  if (props.stockTotal === 0) {
    emit('update:value', 0)
    isZero.value = true
  }
})
</script>

<template>
  <div class="count-box">
    <button class="sub" @click="handleSub" :disabled="isZero">-</button>
    <input class="inp" type="text" :value="value" @change="handleChange" :disabled="isZero"/>
    <button class="add" @click="handleAdd" :disabled="isZero">+</button>
  </div>
</template>

<style scoped lang="less">
.count-box {
  width: 110px;
  display: flex;

  .add, .sub {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }

  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>

<script>
export default {
  name: 'CountBox'
}
</script>
